<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/5/25
 * Time: 10:22
 */
namespace Home\Controller;
use Think\Controller;

define("TOKEN", "yyf15010566605");

class TokenController extends Controller
{
    private $appid;
    private $appsecret;
    private $access_token;
    private $users='';

    public function __construct()
    {
        parent::__construct();
        $this->users=D('Users');
        $this->users->startTrans();
        $tran1 = simplexml_load_file("./weixin/base.xml");
        $this->appid = $tran1->appid;
        $this->appsecret = $tran1->appsecret;
        $this->access_token = $this->isToken();
        $echoStr = $_GET["echostr"];
        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        //extract post data
        if (!empty($postStr)){
            /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
               the best way is to check the validity of xml by yourself */
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $keyword = trim($postObj->Content);
            $time = time();
            $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";
            if(!empty( $keyword ))
            {
                $msgType = "text";
                $contentStr = "Welcome to wechat world!";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            }else{
                echo "Input something...";
            }
        }else {
            echo "";
            exit;
        }
    }

    private function checkSignature()
    {
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }

        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    /*保存access_token*/
    function isToken()
    {
        //载入xml文件
        $tran = simplexml_load_file("./weixin/accessToken.xml");
        $arr['access_token'] = $tran->accessToken;
        $arr['create_data'] = $tran->createData;
        $arr['expires_in'] = $tran->expiresIn;
        $overtime = $arr['create_data'] + $arr['expires_in'];

        if (time() > $overtime) {    // 如果access_token的保存时间超时，重新获取一次

            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($ch);
            curl_close($ch);
            $jsoninfo = json_decode($output, true);
            $jsoninfo['create_data'] = time();

            // 将返回信息保存到xml文件中
            $xml = "<?xml version='1.0' encoding='utf-8'?>
            <node>
            <accessToken>{$jsoninfo['access_token']}</accessToken>
            <expiresIn>{$jsoninfo['expires_in']}</expiresIn>
            <createData>{$jsoninfo['create_data']}</createData>
            </node>";
            $sxe = new \SimpleXMLElement($xml);

            $sxe->asXML('weixin/accessToken.xml');

            $access_token = $jsoninfo['access_token'];
        } else {
            $access_token = $arr['access_token'];
        }
        return $access_token;
    }


    /*
     * 获取用户信息
     * 第一步：获取code
     * */

    //第一步 获取code. 需要 appid
    function getCode()
    {
        //$arr=D("wx_set")->where("id=1")->find();
        $redirect = urlencode("http://www.congliangji.org/ddgc/Home/Token/codeAccessToken");
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appid."&redirect_uri=".$redirect."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        header('location:' . $url);
    }
// https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&redirect_uri=http%3A%2F%2Fnba.bluewebgame.com%2Foauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
    //第二步 通过code 获取accessToken
    function codeAccessToken()
    {
        // 微信GET方式返回code
        $code = $_GET['code'];

//        $arr = D("wx_set")->where("id=1")->find();
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid."&secret=".$this->appsecret."&code=".$code."&grant_type=authorization_code";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        $jsoninfo = json_decode($output, true);     // 将微信返回的json数据，转化为数组
        //$jsoninfo['create_data']=time();
        $this->userInfo($jsoninfo['access_token'], $jsoninfo['openid']);
    }

//    //第三步 获取refresh
//    function refreshToken($refresh_token='')
//    {
//        $url="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={$this->appid}&grant_type=refresh_token&refresh_token={$refresh_token}";
//        $ch=curl_init();
//        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//        $output = curl_exec($ch);
//        curl_close($ch);
//        $jsoninfo = json_decode($output, true);     // 将微信返回的json数据，转化为数组
//        $this->userInfo($jsoninfo['access_token'],$jsoninfo['openid']);
//    }

    //第四步 获取用户微信信息
    function userInfo($access_token = '', $openid = '')
    {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        $jsoninfo = json_decode($output, true);     // 返回用户的  相关信息， 用户信息接口调用完成
        $this->addWxUser($jsoninfo);
    }
    /*获取用户 微信 信息 END*/

    // 通过微信得到的用户数据存入数据库
    function addWxUser($jsoninfo)
    {
        $cond['openid']=$jsoninfo['openid'];
        $yanGone=$this->users->where($cond)->find();
        if($yanGone['nick']!="")    // 用户不是第一次登录，
        {
            echo "-1-"; exit;
            //session("username","临时测试");     // 着两个session 都是临时测试使用
            session("userID",$yanGone['id']);
            session("openID",$yanGone['openid']);
            $this->redirect('Index/lbs');
        }
        else     // 用户第一次登录
        {
            echo "-2-"; exit;
            $data['id']='';
            $data['nick']=$jsoninfo['nickname'];
            $data['sex']=$jsoninfo['sex'];
            $data['head_img']=$jsoninfo['headimgurl'];
            $data['openid']=$jsoninfo['openid'];
            $data['reg_time']=time();
            $aa=$this->users->data($data)->add();
            if($aa){
                $this->users->commit();
            }else{
                $this->users->rollback();
            }
            session("userID",$aa);
            session("openID",$jsoninfo['openid']);
            $this->redirect("Index/lbs");
        }
    }

}